import json
#输出box_b的rectangle
def get_box_b(data):
    result=None
    for box in data["boxes"]:
        if box["name"]=="box_b":
            print(box["rectangle"])
            result=box["rectangle"]
            break
    return result
path="boxes.json"
#解析json对象
data = json.load(open(path))
get_box_b(data)

        
#将任意图片填充到另一个图片对应的box_b的区域
from PIL import Image,ImageDraw
#根据box信息，获取x,y,w,h信息                
def get_loc_msg(im,box_b,draw_box=False):
    width,height=im.size
    x,y=box_b['left_top']
    w=width-box_b['right_bottom'][0]-x
    h=height-box_b['right_bottom'][1]-y
    if draw_box:
        draw = ImageDraw.Draw(im)
        draw.rectangle([x,y,x+w,y+h], outline ="red")
    return (x,y,w,h)
#进行图像粘贴
def paste_img(im1,im2,loc_msg,mode="fill"):   
    x,y,w,h=loc_msg
    if mode=='resize':#进行拉伸填充
        im1=im1.resize((w,h), Image.BICUBIC)
        im2.paste(im1, (x, y))
    elif mode=='fill':#保证长宽比的填充
        ow,oh=im1.size
        if ow*(h/oh)>w:#超长了
            scale=w/ow
            print(scale," height over!")
        else:
            scale=h/oh
            print(scale," width over!")
        w,h=int(ow*scale),int(oh*scale)
        print(w,h)
        im1=im1.resize((w,h), Image.BICUBIC)
        im2.paste(im1, (x, y))
        im2.show()
#图像粘贴的小工具
def paste_tool(im1_path,im2_path,json_path):
    im2_json=json.load(open(json_path))
    im1=Image.open(im1_path)
    im2=Image.open(im2_path)
    box_b=get_box_b(im2_json)
    loc_msg=get_loc_msg(im2,box_b)
    paste_img(im1,im2,loc_msg,mode="fill")

im1_path="B.png"
#im1_path="A.png"
im2_path="boxes.png"
json_path=im2_path.split('.')[0]+'.json'
paste_tool(im1_path,im2_path,json_path)